#!/usr/bin/python
# -*- coding: utf8 -*-

import logging

from pymylib.lib.base import *
from pymylib.model import Session, Biblio, User, Category, BiblioType, BiblioWriteoff, Card
from pymylib.lib.apihelper import *
from __init__ import perPage
from mako.lookup import TemplateLookup
from pylons.templating import render, render_response
from datetime import datetime

lkp = TemplateLookup(directories=['/biblio'], output_encoding='utf-8')

log = logging.getLogger(__name__)

class BiblioController(BaseController):
    template_prefix = '/biblio'
    template_err_prefix = '/error'
    requires_auth = ['index']

    def __before__(self):
        if 'sort_name' not in session:
            session['sort_name'] = "id"
            session.save()
        if 'user' not in session:
            session['user'] = "anonymous"
            session.save()
            redirect_to(action='list')

    def __check_permitions__(self, mode):
        """Check for permitions"""

        # Зарегистрирован-ли пользователь в системе?
        if self.requires_auth and session['user'] == 'anonymous':
            c.error = "Необходимо выполнить вход в систему!"
            return False
        
        if mode == 'add':
            if session['libUser'] or session['librarianUser'] or session['adminAccess']:
                return True
            else: c.error = "Нет прав на выполнение этой операции!"

        if mode == 'edit':
            # Реализовать возможность редактирования своих данных!!!
            if session['librarianUser'] or session['adminAccess']:
                return True
            else:
                c.error = "Нет прав на выполнение этой операции!"

        if mode == 'delete':
            if session['librarianUser'] or session['adminAccess']:
                return True
            else: c.error = "Нет прав на выполнение этой операции!"

        if mode == 'order':
            if 'libUser' in session: return True
          

        
    def index(self):
        """Start method"""
        redirect_to(action='list')

    def sort(self):
        session['sort_name'] = request.params.get('n')
        session.save()
        
        if 'path_before' in session:
            redirect_to(session['path_before'])
        else: redirect_to('list')
    
    def __search__(self, Query):
        try:
            if request.params['id'] is not None and request.params['id'] != "":
                c.searchVal = request.params['id']
            else:
                c.searchErr = unicode('Необходимо установить значение поиска!', encoding='utf8')
                return None
                
            if request.params['by'] == "name":
                c.checked = 1
                if len(c.searchVal) < 3:
                    c.searchErr = unicode('Поисковое значение должно быть больше 3-х!', encoding='utf8')
                    return None
                else:
                    c.searchErr = unicode("Отфильтрованно по подстроке %s", encoding='utf8') % c.searchVal
                    return Query.select(Biblio.c.name.like("%"+"%s" %c.searchVal +"%"), order_by=session['sort_name'])
                
            elif request.params['by'] == "id":
                c.checked = 2
                c.searchErr = unicode("Отфильтрованно по подстроке %s", encoding='utf8') % c.searchVal
                return list(Query.filter_by(id = c.searchVal))
                
        except:
            pass

	def __selectby__(self, Query):
		try:
			if (request.params['category_id'] is not None) and (request.params['category_id'] != ""):
				c.searchVal = request.params['category_id']
                
		except:
			pass	

    def list(self):
        """List of biblio nomenclature"""

        c.curPage = 0
        c.pageTitle = unicode('Библиотека (главная страница)', encoding='utf8')
        c.formCaption = unicode('Список номенклатуры библиотеки', encoding='utf8')

        c.checked = 1 # Значение по умолчанию ...

        categ_q = Session.query(Category)
        c.category = categ_q.all()
                
        #category = categ_q.filter_by(id = c.biblio.category_id).one()
        #c.biblio.category_name = category.name
        
        # Создадим объект - запрос
        biblio_q = Session.query(Biblio)

        #if len(request.params) > 1 and request.params as 'category_id': pass



        if len(request.params) > 1: # and request.params not in 'category_id':
            c.biblioPosts = self.__search__(biblio_q)

            # Проверим результат поиска
            if c.biblioPosts is None:
                return render_response(self.template_prefix + '/list.myt')
        else:
            try:
                #return session['fio']
                #return request.params['ord']
                c.curPage = int(request.params['pg'])-1                                    
                c.biblioPosts = list(biblio_q.select(Biblio.c.write_off == None, order_by=session['sort_name'])[perPage*c.curPage:perPage*(c.curPage+1)])
                #c.biblioPosts = list(biblio_q.filter_by(write_off = None)[perPage*c.curPage:perPage*(c.curPage+1)])
            except:
                c.biblioPosts = biblio_q.select(Biblio.c.write_off == None, limit=perPage, order_by=session['sort_name'])
                #c.biblioPosts = list(biblio_q.filter_by(write_off = None).limit(perPage))        
         
            ''' Получим страницы с диапазоном заданным perPage '''
            c.pages = []
            i = 0

            for bib in c.biblioPosts[:int(biblio_q.count()/perPage)+1]:
                i = i+1
                c.pages.append(i)

        if (len(c.pages) == 0) or (len(c.pages) == 1):
            c.pages = None

        ''' ---------------------------------------------- '''
        c.currentUser = None
        c.user_id = None
        if 'user_id' in session:
            c.user_id = session['user_id']
        if 'fio' in session:
            c.user_name = session['fio']

        session['path_before'] = request.path_info + '?' + request.environ['QUERY_STRING']
        session.save()

        return render_response(self.template_prefix + '/list.myt')

    def fullview(self, id):
        """Show full view biblio object by objID

        integer id - object ID
        """ 
        biblio_q = Session.query(Biblio)
        c.biblio = biblio_q.filter_by(id = id).one()
        
        bt_q = Session.query(BiblioType)
        biblio_type = bt_q.filter_by(id = c.biblio.biblio_type_id).one()
        c.biblio.type_name = biblio_type.name

        categ_q = Session.query(Category)
        category = categ_q.filter_by(id = c.biblio.category_id).one()
        c.biblio.category_name = category.name

        return render_response(self.template_prefix + '/fullinfo.myt')

    def add(self):
        """Visual method adding object"""
        if self.__check_permitions__('add') != True:
            c.index = 'add'
            return render(self.template_err_prefix + '/error.mako')
        
        c.biblio = None
        category_q = Session.query(Category)
        c.category = list(category_q.all())

        bt_q = Session.query(BiblioType)
        c.bibliotype = list(bt_q.all())
        return render_response(self.template_prefix + '/edit.myt')

    def create(self):
        """Insert object to datebase"""
        
        if self.__check_permitions__('add') != True:
            return render(self.template_err_prefix + '/error.mako')
        

        new_biblio = Biblio()
        
        new_biblio.biblio_type_id = int(request.params['biblio_type_id'])
        new_biblio.category_id = int(request.params['category_id'])

        if 'user_id' in session:
            new_biblio.owner_id = session['user_id']
        else: raise "Ошибка! Невозможно получить идентификатор текущего пользователя!"
        
        new_biblio.private = 0

        if request.params['name'] == "": raise "Поле Наименование должно быть заполнено!"
        else: new_biblio.name = request.params['name']
        
        if request.params['author'] == "": new_biblio.author = None
        else: new_biblio.author = request.params['author']

        if request.params['year'] == "": new_biblio.year = None
        else: new_biblio.year = request.params['year']

        if request.params['pages'] == "": new_biblio.pages = None
        else: new_biblio.pages = int(request.params['pages'])
            
        if request.params['publishing'] == "": new_biblio.publishing = None
        else: new_biblio.publishing = request.params['publishing']

        if request.params['place'] == "": new_biblio.place = None
        else: new_biblio.place = request.params['place']

        if request.params['annote'] == "": new_biblio.annote = None
        else: new_biblio.annote = request.params['annote']
        
        if request.params['note'] == "": new_biblio.note = None
        else: new_biblio.note = request.params['note']
        
        new_biblio.date_add = datetime.now()
        
        try:
            Session.save(new_biblio)
            Session.commit()
        except:
            Session.rollback()
            raise
        if 'path_before' in session:
            redirect_to(session['path_before'])
        else: redirect_to('list')

    def order(self, id):
        if self.__check_permitions__('order') != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        biblio_q = Session.query(Biblio)
        c.biblio = biblio_q.filter_by(id = id).one()
        
        return render_response(self.template_prefix + '/order.mako')
        
    def do_order(self, id):

        if self.__check_permitions__('order') != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')
        
        new_order = Card()
        new_order.biblio_id = id
        new_order.user_id = session['user_id']

        #new_order.order_expiry_date = datetime.now()

        new_order.order_date = datetime.now()
        
        try:
            Session.save(new_order)
            Session.commit()
        except:
            Session.rollback()
            raise
        
        redirect_to('../../order')

    def delete(self, id):
        """Visual method deleting object by id"""
        if self.__check_permitions__('delete') != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        biblio_q = Session.query(Biblio)
        c.biblio = biblio_q.filter_by(id = id).one()

        return render_response(self.template_prefix + '/writeOff.myt')

    def writeoff(self, id):
        """Write off object by id"""

        if self.__check_permitions__('delete') != True:
            return render(self.template_err_prefix + '/error.mako')

        biblio_q = Session.query(Biblio)
        wtiteof_biblio = biblio_q.filter_by(id = id).one()
        wtiteof_biblio.write_off = datetime.now()
        
        if request.params['reason'] == "": raise 
        else: wtiteof_biblio.reason = request.params['reason']
        try:
            Session.commit()
        except:
            raise

        if 'path_before' in session:
            redirect_to(session['path_before'])
        else: redirect_to('list')
        #redirect_to('../list') 

    def edit(self, id):
        """Visual method editing object by ID"""
        if self.__check_permitions__('edit') != True:
            c.index = 'fullview'+id
            return render(self.template_err_prefix + '/error.mako')

        biblio_q = Session.query(Biblio)
        c.biblio = biblio_q.get_by(id=id)

        category_q = Session.query(Category)
        c.category = list(category_q.all())

        bt_q = Session.query(BiblioType)
        c.bibliotype = list(bt_q.all())

        return render_response(self.template_prefix + '/edit.myt')

    def update(self, id):
        """Updates object to database by ID"""

        if self.__check_permitions__('edit') != True:
            return render(self.template_err_prefix + '/error.mako')

        biblio_q = Session.query(Biblio)
        
        #biblio_q._connection.debug = True
        biblio_obj = biblio_q.get_by(id=id)

        biblio_obj.biblio_type_id = int(request.params['biblio_type_id'])
        biblio_obj.category_id = int(request.params['category_id'])

        biblio_obj.private = 0

        if request.params['name'] == "": raise
        else: biblio_obj.name = request.params['name']
        
        if request.params['author'] == "": biblio_obj.author = None
        else: biblio_obj.author = request.params['author']

        if request.params['year'] == "": biblio_obj.year = None
        else: biblio_obj.year = request.params['year']

        if request.params['pages'] == "": biblio_obj.pages = None
        else: biblio_obj.pages = int(request.params['pages'])
            
        if request.params['publishing'] == "": biblio_obj.publishing = None
        else: biblio_obj.publishing = request.params['publishing']

        if request.params['place'] == "": biblio_obj.place = None
        else: biblio_obj.place = request.params['place']

        if request.params['annote'] == "": biblio_obj.annote = None
        else: biblio_obj.annote = request.params['annote']
        
        if request.params['note'] == "": biblio_obj.note = None
        else: biblio_obj.note = request.params['note']

        try:
            Session.commit()
        except:
            Session.rollback()
            raise #"Ошибка при сохранении в базу данных"
        
        if 'path_before' in session:
            redirect_to(session['path_before'])
        else: redirect_to('list')

    def select(self):
        """List of biblio nomenclature for select"""
        c.curPage = 0
        c.pageTitle = unicode('Выбор номенклатуры библиотеки', encoding='utf8')
        c.formCaption = c.pageTitle
        c.user_id = None

        biblio_q = Session.query(Biblio)
        try:
            c.curPage = int(request.params['pg'])-1
            c.biblioPosts = list(biblio_q.filter_by(write_off = None)[perPage*c.curPage:perPage*(c.curPage+1)])
        except:
            c.biblioPosts = list(biblio_q.filter_by(write_off = None).limit(perPage))


        c.pages = []
        i = 0
        for bib in c.biblioPosts[:int(biblio_q.count()/perPage)+1]:
            i = i+1
            c.pages.append(i)

        if len(c.pages) == 1:
            c.pages = None

        return render_response(self.template_prefix + '/select.myt')
        
